package cn.s1995.sloth.app.controller;

import cn.hutool.core.util.StrUtil;
import cn.s1995.sloth.common.core.constant.enums.hint.Hint;
import cn.s1995.sloth.bizs.entity.UserAddress;
import cn.s1995.sloth.bizs.entity.base.BaseEntity;
import cn.s1995.sloth.bizs.exception.BizException;
import cn.s1995.sloth.bizs.service.UserAddressService;
import cn.s1995.sloth.common.core.util.R;
import cn.s1995.sloth.common.security.util.SecurityUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * CommonController
 *
 * @author Lex
 * @description 我的
 * @date 2023/12/23 17:14
 */
@RestController
@RequestMapping("/m/my/address")
@RequiredArgsConstructor
@Tag(description = "MyController", name = "APP-我的地址")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class ApiMyAddressController {

    private final UserAddressService userAddressService;

    @ApiOperationSupport(order = 10)
    @Operation(summary = "我的地址-分页", description = "我的地址-分页")
    @GetMapping("/page")
    public R<IPage<UserAddress>> getPageMyAddress(@ParameterObject Page page, @ParameterObject UserAddress req) {
        LambdaQueryWrapper<UserAddress> wrapper = buildQueryWrapper(req);

        return R.ok(userAddressService.page(page, wrapper));
    }

    @ApiOperationSupport(order = 11)
    @Operation(summary = "我的地址-列表", description = "我的地址-列表")
    @GetMapping("/list")
    public R<List<UserAddress>> getListMyAddress(@ParameterObject UserAddress req) {
        LambdaQueryWrapper<UserAddress> wrapper = buildQueryWrapper(req);

        return R.ok(userAddressService.list(wrapper));
    }

    @ApiOperationSupport(order = 12)
    @Operation(summary = "我的地址-获取地址信息", description = "我的地址-获取地址信息")
    @GetMapping("/{addressId}")
    public R<UserAddress> getOneMyAddress(@PathVariable Long addressId) {
        return R.ok(userAddressService.getUserAddrByUserId(addressId, SecurityUtils.getUser().getId()));
    }


    @ApiOperationSupport(order = 13)
    @Operation(summary = "我的地址-添加", description = "我的地址-添加")
    @PostMapping
    public R saveMyAddress(@RequestBody @Validated(BaseEntity.ValidGroup.Add.class) UserAddress req) {
        userAddressService.saveAddress(req);
        return R.ok();
    }
    @ApiOperationSupport(order = 14)
    @Operation(summary = "我的地址-编辑", description = "我的地址-编辑")
    @PutMapping
    public R editMyAddress(@RequestBody @Validated(BaseEntity.ValidGroup.Edit.class) UserAddress req) {
        userAddressService.updateAddress(req);
        return R.ok();
    }

    @ApiOperationSupport(order = 15)
    @Operation(summary = "我的地址-删除", description = "我的地址-删除")
    @DeleteMapping("/{addressId}")
    public R editMyAddress(@PathVariable Long addressId) {
        Long userId = SecurityUtils.getUser().getId();
        UserAddress userAddress = userAddressService.getUserAddrByUserId(addressId, userId);
        if (Objects.isNull(userAddress)) {
            throw new BizException(Hint.APP_USER_ADDRESS_NOT_EXIST);
        }
        // if (userAddress.getIsDefaulted()) {
        //     throw new BizException(Hint.APP_USER_ADDRESS_IS_DEFAULTED);
        // }
        userAddressService.removeById(addressId);
        userAddressService.removeCacheUserAddressByUserId(addressId, userId);
        // 默认地址删除缓存
        if (userAddress.getIsDefaulted()) {
            userAddressService.removeCacheUserAddressByUserId(0L, userId);
        }
        return R.ok();
    }

    @ApiOperationSupport(order = 16)
    @Operation(summary = "我的地址-设置默认地址", description = "我的地址-设置默认地址")
    @PutMapping("/{addressId}/default")
    public R defaultAddr(@PathVariable Long addressId) {
        Long userId = SecurityUtils.getUser().getId();

        userAddressService.updateDefaultUserAddr(addressId, userId);

        userAddressService.removeCacheUserAddressByUserId(0L, userId);
        userAddressService.removeCacheUserAddressByUserId(addressId, userId);
        return R.ok();
    }

    /**
     * 构建查询条件
     * @param req
     * @return
     */
    @NotNull
    private static LambdaQueryWrapper<UserAddress> buildQueryWrapper(UserAddress req) {
        LambdaQueryWrapper<UserAddress> wrapper = Wrappers.lambdaQuery(UserAddress.class)
                .eq(UserAddress::getUid, SecurityUtils.getUser().getId());
        wrapper.and(
                StrUtil.isNotEmpty(req.getSearch()),
                w -> w.like(UserAddress::getReceiver, req.getSearch())
                        .or()
                        .like(UserAddress::getPhone, req.getSearch())
                        .or()
                        .like(UserAddress::getProvince, req.getSearch())
                        .or()
                        .like(UserAddress::getCity, req.getSearch())
                        .or()
                        .like(UserAddress::getArea, req.getSearch())
                        .or()
                        .like(UserAddress::getStreet, req.getSearch())
                        .or()
                        .like(UserAddress::getAddress, req.getSearch())
        );
        return wrapper;
    }

}
